package net.woggle.shackbrowse.notifier;

import java.util.ArrayList;

import com.commonsware.cwac.wakeful.WakefulIntentService;

import net.woggle.shackbrowse.MainActivity;
import net.woggle.shackbrowse.R;
import net.woggle.shackbrowse.SearchResult;
import net.woggle.shackbrowse.ShackApi;

import android.app.Activity;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

public class NotifierService extends WakefulIntentService {
	private NotifierService _activity;
	private SharedPreferences _prefs;
	private String SBTAG = "SBNOTIFIER";
	private boolean _enabled = true;
	
	public NotifierService ()
	{
		super("ShackBrowse Notifier Service");
	}
	
	@Override
	public void onCreate ()
	{
		super.onCreate();
		_activity = this;
		_prefs = PreferenceManager.getDefaultSharedPreferences(_activity);
		_enabled = _prefs.getBoolean("notifyEnabled", true);
		Log.d(SBTAG, SBTAG+": " + " Created");
	}
	@Override
	protected void doWakefulWork(Intent intent) {
		Log.d(SBTAG, SBTAG+": " + "Received intent");
		// disabled
		if (false)
		{
			Log.d(SBTAG, SBTAG+": " + "Enabled");
			Exception _exception = null;
			ArrayList<SearchResult> result;
			try
	        {
	        	String userName = _prefs.getString("userName", "").trim();
	        	result = ShackApi.notify_search("", "", userName, "", 0, _activity);
	        }
	        catch (Exception e)
	        {
	            Log.e(SBTAG, "Error doing notifications", e);
	            _exception = e;
	            result = null;
	        }
			if (_exception != null)
	        {
	        	System.out.println("notifications: error");
	        }
	        else if (result == null)
	        {
	        	System.out.println("notifications: error");
	        }
	        else
	        {
	        	Log.d(SBTAG, SBTAG+": " + "Processing");
	        	int lastSeenNotificationId = _prefs.getInt("notifyLastSeenReplyId", 0);
	        	int newReplies = 0;
	        	String replyFrom = "";
	        	int idFrom = 0;
	        	for (int i = 0; i < result.size(); i++)
	        	{
	        		if (result.get(i).getPostId() == lastSeenNotificationId)
	        			break;
	        		
	        		if (newReplies == 0)
	        		{
		        		replyFrom = result.get(i).getAuthor();
		        		idFrom = result.get(i).getPostId();
	        		}
	        		newReplies ++;
	        	}
	        	
	        	if (newReplies > 0)
	        	{
	        		Log.d(SBTAG, SBTAG+": " + "Firing Notification");
	        		
	            	NotificationCompat.Builder mBuilder =
	            	        new NotificationCompat.Builder(_activity)
	            	        .setSmallIcon(R.drawable.icon)
	            	        .setContentTitle("New Reply")
	            	        .setContentText(replyFrom + " replied to your post")
	            	        .setAutoCancel(true);
	            	
	            	
	            	// Creates an explicit intent for an Activity in your app
	            	Intent resultIntent = new Intent(_activity, MainActivity.class);
	            	resultIntent.putExtra("notificationOpenId", idFrom);
	            		
	            		
	            	if (newReplies > 1)
	            	{
	            		mBuilder.setContentTitle("New Replies");
	            		mBuilder.setContentText("Click to show a list");
	            		resultIntent.putExtra("notificationOpenParentAuthorSearch", true);
	            		
	            	}
	            	
	            	resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
	            	
	            	// The stack builder object will contain an artificial back stack for the
	            	// started Activity.
	            	// This ensures that navigating backward from the Activity leads out of
	            	/* your application to the Home screen.
	            	TaskStackBuilder stackBuilder = TaskStackBuilder.create(_activity);
	            	// Adds the back stack for the Intent (but not the Intent itself)
	            	stackBuilder.addParentStack(MainActivity.class);
	            	// Adds the Intent that starts the Activity to the top of the stack
	            	stackBuilder.addNextIntent(resultIntent);
	            	PendingIntent resultPendingIntent =
	            	        stackBuilder.getPendingIntent(
	            	            0,
	            	            PendingIntent.FLAG_UPDATE_CURRENT
	            	        );
	            	88888*/
	            	PendingIntent resultPendingIntent = PendingIntent.getActivity(_activity, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
	            	
	            	mBuilder.setContentIntent(resultPendingIntent);
	            	NotificationManager mNotificationManager =
	            	    (NotificationManager) _activity.getSystemService(Context.NOTIFICATION_SERVICE);
	            	
	            	Notification notification = mBuilder.build();
	            	notification.defaults|= Notification.DEFAULT_SOUND;
	            	notification.defaults|= Notification.DEFAULT_VIBRATE;
	            	notification.flags |= Notification.FLAG_SHOW_LIGHTS;
	            	notification.ledARGB = Color.GREEN;
	            	notification.ledOffMS = 1500;
	            	notification.ledOnMS = 100;
	            	// mId allows you to update the notification later on.
	            	int mId = 58401;
	            	mNotificationManager.notify(mId, notification);
	        	}
	        	else
	        	{
	        		Log.d(SBTAG, SBTAG+": " + "NO new replies");
	        	}
	        }
		}
	}
}